<?php

namespace app\index\controller\wanlshop;
use app\common\controller\Wanlshop;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Chargecard extends Wanlshop
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\wanlshop\ChargeCard();
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['user'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
   public function add()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isPost()) {
                set_time_limit(0);
                $params = $this->request->post("row/a");
                $head_number = $params['head_number'];
                $start_number = intval($params['start_number']);
                $end_number = intval($params['end_number']);
                if($end_number<$start_number){
                    $this->error("结束卡号不能小于起始卡号");
                }
                $balance_money = empty($params['balance_money'])?0:(int)$params['balance_money'];
                $card =model('app\common\model\wanlshop\ChargeCard');
                if($this->shop->id){
                    $tmp_data['shop_id']=$this->shop->id;
                }
                $tmp_data['balance_money']=$balance_money;
                $data_arr =[];
                $i = $start_number;
                $h = 1;
                while($i<=$end_number){
                    $data = $tmp_data;
                    $data['card_no']= $head_number.str_pad($i,6,"0",STR_PAD_LEFT);
                    $data['cardpass']= rand(10000000,99999999);
                    $data_arr[]  = $data;
                    if($h%10000==0){
                        if(!$card->saveAll($data_arr)){
                            $return =['error'=>true,'msg'=>"添加实体卡失败!"];
                            break;
                        }else{
                            $return =['error'=>false,'msg'=>"添加成功!"];
                        }
                        $data_arr =[];
                    }
                    $i++;
                    $h++;
                }

                if(!empty($data_arr)){
                    if(!$card->saveAll($data_arr)){
                        $return =['error'=>true,'msg'=>"添加实体卡失败"];
                    }else{
                        $return =['error'=>false,'msg'=>"添加成功!"];
                    }
                }

                if(!$return['error']){
                    $this->success($return['msg']);
                }else{
                    $this->error($return['msg']);
                }

        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     * @param $ids
     * @return string
     * @throws Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['shop_id'] !=$this->shop->id) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $user=$this->auth->getUser();
            $params=$this->request->post("row/a");
            $des='';
            if(isset($params['cardpass'])) {
                $row['cardpass']=$params['cardpass'];
                $des.=$row['cardpass'] == $params['cardpass'] ? "" : "密码从{$row['cardpass']}修改为{$params['cardpass']},";
            }
            $row['balance_money']=$params['balance_money']??$row['balance_money'];
            $row['status']=$params['status'];

            $log['user_id'] =$user['id'];
            $log['card_no'] = $row['card_no'];
            $log['shop_id'] =$this->shop->id;
            $des.= '当前金额为'.$row['balance_money'];
            $des.=',当前状态为'.$this->model->getTypeList()[$row['status']];
            $log['des'] = '账号'.$user['username'].'操作,'.$des;

            Db::startTrans();
            $res1=$row->save();
            $res2=model('app\common\model\wanlshop\ChargeCardLog')->create($log);
            if(!$res1 || !$res2) {
                Db::rollback();
                $this->error('保存失败');
            }
            Db::commit();
            $this->success('保存成功！');
        }
        $row['user_id']=$row['user_id']??'暂无';
        $row['nickname']=$row->user?$row->user->nickname:'暂无';
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    public function del($ids = "")
    {
        if ($ids) {
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            if ($row['shop_id'] !=$this->shop->id) {
                $this->error(__('You have no permission'));
            }
            if($row['user'] && $row['is_bind'] && $row['activetime'])$this->error('已激活卡不能删除!');

            $user=$this->auth->getUser();
            $log['user_id'] =$user['id'];
            $log['card_no'] = $row['card_no'];
            $des=',删除了当前卡号'.$row['card_no'];
            $log['des'] = '账号'.$user['username'].'操作,'.$des;

            Db::startTrans();
            $res1=$row->delete();
            $res2=model('app\common\model\wanlshop\ChargeCardLog')->create($log);
            if(!$res1 || !$res2) {
                Db::rollback();
                $this->error('未删除任何行!');
            }
            Db::commit();
            $this->success('删除成功!');
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }



}